package com.z.sys.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.github.pagehelper.PageInfo;
import com.z.common.aop.annotation.Log;
import com.z.common.aop.enums.BusinessType;
import com.z.common.utils.ExcelUtil;
import com.z.common.web.base.BaseController;
import com.z.common.web.vo.request.PageVo;
import com.z.common.web.vo.response.Result;
import com.z.sys.entity.Dept;
import com.z.sys.service.IDeptService;
import com.z.sys.vo.DeptExcelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 机构管理Controller
 *
 * @author z
 * @date 2022-11-07
 */
@RestController
@RequestMapping("/system/dept")
@Api(tags = "机构管理")
public class DeptController extends BaseController {

    private String prefix = "system/dept";

    @Autowired
    private IDeptService deptService;

    @GetMapping("/main")
    @PreAuthorize("hasPermission('/sys/dept/main','sys:dept:main')")
    @ApiOperation(value = "查询页面")
    public ModelAndView main() {
        return jumpPage(prefix + "/main");
    }

    @GetMapping("/main_tree")
    @PreAuthorize("hasPermission('/sys/dept/main_tree','sys:dept:main')")
    @ApiOperation(value = "查询页面-机构树展示，数据量大非常卡")
    public ModelAndView main_tree() {
        return jumpPage(prefix + "/main_tree");
    }

    /**
     * 查询机构管理列表
     */
    @ResponseBody
    @GetMapping("/data")
    @PreAuthorize("hasPermission('/sys/dept/data','sys:dept:main')")
    @ApiOperation(value = "查询接口")
    @Log(title = "机构管理", describe = "查询机构数据Page", type = BusinessType.QUERY)
    public Result data(@ModelAttribute Dept dept, PageVo pageVo) {
        PageInfo<Dept> pageInfo = deptService.selectDeptPage(dept, pageVo, "人事");
        return Result.table(pageInfo);
    }
    /**
     * 按条件下载
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasPermission('/sys/dept/export','sys:dept:main')")
    @ApiOperation(value = "导出接口")
    @PostMapping(value = "/export")
    public void export(@ModelAttribute Dept dept, HttpServletRequest request, HttpServletResponse response) {
        List<DeptExcelVo> deptList = deptService.selectDeptInfoList(dept);
        ExcelUtil.write(response,"DeptExport", DeptExcelVo.class, deptList);
    }

    /**
     * 导入机构
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ResponseBody
    @PreAuthorize("hasPermission('/sys/dept/upload','sys:dept:import')")
    @ApiOperation(value = "导入接口")
    @Log(title = "机构管理", describe = "导入机构", type = BusinessType.ADD)
    public Result upload(MultipartFile file) throws IOException {
            EasyExcel.read(file.getInputStream(), DeptExcelVo.class, new PageReadListener<DeptExcelVo>(dataList -> {
                List<Dept> deptList = new ArrayList<>();

                dataList.forEach(data ->{
                    Dept d = new Dept();
                    BeanUtils.copyProperties(data, d);
                    d.setStatus("1");
                    d.setFullPath(data.getParentCode());
                    deptList.add(d);
                });
                deptService.saveToDB(deptList);

            })).sheet().doRead();
        return Result.success();
    }
    /**
     * 查询机构管理列表
     */
    @ResponseBody
    @GetMapping("/list")
    @PreAuthorize("hasPermission('/sys/dept/list','sys:dept:main')")
    @ApiOperation(value = "查询接口")
    @Log(title = "机构管理", describe = "查询机构数据list", type = BusinessType.QUERY)
    public Result list(@ModelAttribute Dept dept, PageVo pageVo) {
        pageVo.setLimit(99999);
        PageInfo<Dept> pageInfo = deptService.selectDeptPage(dept, pageVo, "人事");
        return Result.table(pageInfo);
    }
    /**
     * 查询权限内机构树--只要单位
     */
    @ResponseBody
    @GetMapping("/unitTree")
    @ApiOperation(value = "查询权限内单位树")
    @Log(title = "机构管理", describe = "查询树状单位数据", type = BusinessType.QUERY)
    public Result unitTree(String model) {
        List<Dept> list = deptService.getUnitListByRole(model);

        return Result.table(200, list);
    }
    /**
     * 查询权限内机构树
     */
    @ResponseBody
    @GetMapping("/tree")
    @ApiOperation(value = "查询权限内机构树")
    @Log(title = "机构管理", describe = "查询树状机构数据", type = BusinessType.QUERY)
    public Result tree(@ModelAttribute Dept dept) {
        List<Dept> list = deptService.getDeptListByRole();
        return Result.table(200, list);
    }

    /**
     * 新增机构管理
     */
    @GetMapping("/add")
    @PreAuthorize("hasPermission('/sys/dept/add','sys:dept:add')")
    @ApiOperation(value = "添加页面")
    public ModelAndView add() {
        return jumpPage(prefix + "/add");
    }

    /**
     * 新增机构管理
     */
    @ResponseBody
    @PostMapping("/save")
    @PreAuthorize("hasPermission('/sys/dept/save','sys:dept:add')")
    @ApiOperation(value = "添加接口")
    @Log(title = "机构管理", describe = "新增机构数据", type = BusinessType.ADD)
    public Result save(@RequestBody Dept dept) {
        if(deptService.save(dept)){
            dept.setFullPath(deptService.getById(dept.getParentId()).getFullPath() + "/" + dept.getId());
            deptService.updateById(dept);
        }
        return new Result(1,"成功");
    }

    /**
     * 修改机构管理
     */
    @GetMapping("/edit")
    @PreAuthorize("hasPermission('/sys/dept/edit','sys:dept:edit')")
    @ApiOperation(value = "修改页面")
    public ModelAndView edit(Long id, ModelMap map) {
        Dept dept =deptService.getById(id);
        map.put("dept", dept);
        return jumpPage(prefix + "/edit");
    }

    /**
     * 修改机构管理
     */
    @ResponseBody
    @PutMapping("/update")
    @PreAuthorize("hasPermission('/sys/dept/update','sys:dept:edit')")
    @ApiOperation(value = "修改接口")
    @Log(title = "机构管理", describe = "修改机构数据", type = BusinessType.EDIT)
    public Result update(@RequestBody Dept dept) {
        if(null!=dept.getParentId() && 0!=dept.getParentId()){
            dept.setFullPath(deptService.getById(dept.getParentId()).getFullPath() + "/" + dept.getId());
        }else if( dept.getId() == 1){
            dept.setFullPath(dept.getId()+"");
        }
        return Result.decide(deptService.updateById(dept));
    }

    /**
     * 删除机构管理
     */
    @ResponseBody
    @DeleteMapping("/batchRemove")
    @PreAuthorize("hasPermission('/sys/dept/batchRemove','sys:dept:del')")
    @ApiOperation(value = "批量删除接口")
    @Log(title = "机构管理", describe = "批量删除机构数据", type = BusinessType.REMOVE)
    public Result batchRemove(String ids) {
        return Result.decide(deptService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 删除机构管理
     */
    @ResponseBody
    @DeleteMapping("/remove/{id}")
    @PreAuthorize("hasPermission('/sys/dept/remove','kq:dept:del')")
    @ApiOperation(value = "删除接口")
    @Log(title = "机构管理", describe = "删除机构数据", type = BusinessType.REMOVE)
    public Result remove(@PathVariable("id") Long id) {
        return Result.decide(deptService.removeById(id));
    }
}
